<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px;" v-model="data.username" placeholder="请输入账号查询"
                prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px;margin-left: 5px" v-model="data.name"
                placeholder="请输入名称查询" prefix-icon="Search"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">查 询</el-button>
      <el-button type="info" style="margin-left: 5px" @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-upload style="display: inline-block;margin-left: 10px"
                 :action="`${BASE_URL}/admin/import`"
                 :show-file-list="false"
                 :on-success="handleImportSuccess">
        <el-button type="success">批量导入</el-button>
      </el-upload>
      <el-button type="info" style="background-color: #7e55fc;margin-left: 10px" @click="exportData">批量导出</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px; width: 100%;">
      <el-table
          :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
          :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="username" label="账号"/>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="phone" label="电话"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column prop="updateTime" label="修改时间"/>
        <el-table-column label="操作" width="100px">
          <template #default="scope">
            <el-button type="primary" icon="edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="delete" circle @click="del(scope.row.id)"></el-button>

          </template>
        </el-table-column>

        <!--      <el-table-column prop="address" label="地址" width="180"/>-->
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :page-sizes="[5, 20, 30, 40, 50, 100]"
          :total="data.total"
          @size-change="load"
          @current-change="load"/>
    </div>

    <el-dialog v-model="data.adminFormVisible" title="管理员信息" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px"
               style="padding: 20px 30px 20px 0">
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.form.username" autocomplete="off" :disabled="!!data.form.id"/>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="data.form.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="data.form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="data.form.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="data.form.email" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.adminFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  username: null,
  name: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  adminFormVisible: false,
  form: {},
  rules: {
    username: [{required: true, message: '请填写账号', trigger: 'blur'}],
    // password: [{required: true, message: '请填写密码', trigger: 'blur'}],
  },
  rows: []
})

const formRef = ref()
const load = () => {
  request.get('/admin/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      username: data.username,
      name: data.name
    }
  }).then(res => {
    // console.log(res)
    if (res.code === '200') {
      // ElMessage.success('请求成功')
      data.tableData = res.data.records
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()
const reset = () => {
  data.name = null
  data.username = null
  load()
}

const handleAdd = () => {
  data.adminFormVisible = true
  data.form = {}
}

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/admin/add', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('新增成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))//深度拷贝数据
  data.adminFormVisible = true
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/admin/update', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('修改成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/admin/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const handleSelectionChange = (rows) => {
  data.rows = rows
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  // 只提取需要的ID列表，减少数据传输
  const ids = data.rows.map(row => row.id)
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.post('/admin/deleteBatch', ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const exportData = () => {
  // 判断是否有选中的数据
  if (data.rows.length > 0) {
    // 导出选中的数据：提取选中项的ID，拼接成参数
    const ids = data.rows.map(item => item.id).join(',');
    const url = `${BASE_URL}/admin/export?ids=${ids}`;
    window.open(url);
  } else {
    // 没有选中数据时，按原条件导出（按username筛选）
    let url = `${BASE_URL}/admin/export?username=${data.username === null ? '' : data.username}`
    window.open(url);
  }
}

const handleImportSuccess = (res) => {
  if (res.code==='200'){
    ElMessage.success('批量导入成功')
  }else {
    ElMessage.error(res.msg)
  }
  load()
}
</script>

<style scoped>

</style>